package de.openkanban.client.ui.adminpanel;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.PasswordItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.TextItem;

import de.openkanban.client.ui.presenter.LogInRequestCallback;
import de.openkanban.client.ui.presenter.PreparedRequest;
import de.openkanban.client.util.Md5Utils;

/**
 * GUI Element for the LoginForm
 */
public class LoginForm extends DynamicForm {

	private StaticTextItem message;

	private PasswordItem password;
	private TextItem email;

	public LoginForm() {

		email = new TextItem();
		email.setName("email");
		email.setTitle("Email");
		email.setValue("hammertime@stop.de");
		email.setRequired(true);

		password = new PasswordItem();
		password.setName("password");
		password.setTitle("Password");
		password.setValue("hh");
		password.setRequired(true);

		message = new StaticTextItem();
		message.setValue("email or password invalid!");
		message.setTitle("Error:");
		message.setTextAlign(Alignment.LEFT);
		message.setColSpan(2);
		message.setTextBoxStyle("failedMessage");
		message.setVisible(false);

		// form
		setHeight100();
		setWidth100();
		setPadding(3);
		setColWidths("60%", "40%");
		setLayoutAlign(VerticalAlignment.BOTTOM);
		setFields(new FormItem[] { email, password, message });
	}

	@Override
	public void submit() {
		if (validate()) {
			String md5Password = Md5Utils.md5(password.getValueAsString());
			PreparedRequest preparedRequest = new PreparedRequest("user", "login", "email", email.getValueAsString(),
					"password", md5Password);
			preparedRequest.sendAsyncRequest(new LogInRequestCallback());
		}
	}

	public StaticTextItem getMessage() {
		return message;
	}

}
